package com.xmut.mall.product.service.impl;

import com.xmut.mall.product.entity.AttrAttrgroupRelationEntity;
import com.xmut.mall.product.entity.AttrEntity;
import com.xmut.mall.product.service.AttrAttrgroupRelationService;
import com.xmut.mall.product.service.AttrService;
import com.xmut.mall.product.utils.RespBean;
import com.xmut.mall.product.vo.AttrGroupWithAttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.product.utils.PageUtils;
import com.xmut.mall.product.utils.Query;

import com.xmut.mall.product.dao.AttrGroupDao;
import com.xmut.mall.product.entity.AttrGroupEntity;
import com.xmut.mall.product.service.AttrGroupService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        //select * from pms_attr_group where catelog_id=? and (attr_group_id=key or attr_group_name like %key%)
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }

        if( catelogId == 0){
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        }else {
            wrapper.eq("catelog_id",catelogId);
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        }
    }

    /**
     * 根据分类id查出所有的分组，以及这些分组里面的属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //1、查询分组信息
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        //2、查询所有属性
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map(group -> {
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(group,attrsVo);
            List<AttrEntity> attrs = attrService.getRelationAttr(attrsVo.getAttrGroupId());
            attrsVo.setAttrs(attrs);
            return attrsVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 获取分组的分页数据
     * @param params
     * @return
     */
    @Override
    public RespBean getAttrGroupByPage(Map<String, Object> params) {
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper();

        // 模糊匹配分组名
        if(!StringUtils.isEmpty(String.valueOf(params.get("key"))) && !String.valueOf(params.get("key")).equals("null")){
            queryWrapper.like("attr_group_name", String.valueOf(params.get("key")));
        }
        // 模糊匹配分类id
        if(!StringUtils.isEmpty(String.valueOf(params.get("cateId"))) && !String.valueOf(params.get("cateId")).equals("null")){
            queryWrapper.eq("catelog_id", String.valueOf(params.get("cateId")));
        }

        IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), queryWrapper);

        return RespBean.success("获取成功", new PageUtils(page));
    }

    /**
     * 添加分组
     * @param entity
     * @return
     */
    @Override
    public RespBean addGroup(AttrGroupEntity entity) {
        boolean save = this.save(entity);
        if (save){
            return RespBean.success("添加分组成功");
        }else {
            return RespBean.error("添加分组失败");
        }

    }

    /**
     * 修改分组
     * @param entity
     * @return
     */
    @Override
    public RespBean editGroup(AttrGroupEntity entity) {
        boolean b = this.updateById(entity);
        if (b){
            return RespBean.success("修改成功");
        }else {
            return RespBean.error("修改失败");
        }
    }

    /**
     * 根据id 删除分组 以及关联表中的分组信息
     * @param attrGroupId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean deleteGroup(Long attrGroupId) {
        // 先删除关联表中的信息
        attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

        // 再删除分组
        boolean b = this.removeById(attrGroupId);
        if (b){
            return RespBean.success("删除成功");
        }else {
            return RespBean.error("删除失败");
        }
    }

    /**
     * 根据分类的id获取分组以及各个分组所拥有的的attr属性
     * @param cateId
     * @return
     */
    @Override
    public RespBean getGroupAndGroupOwnerAttr(Long cateId) {
        List<AttrGroupEntity> groupList = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", cateId));

        List<AttrGroupWithAttrsVo> result = groupList.stream().map(item -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            vo.setAttrGroupId(item.getAttrGroupId());
            vo.setAttrGroupName(item.getAttrGroupName());
            vo.setSort(item.getSort());
            vo.setDescript(item.getDescript());
            vo.setIcon(item.getIcon());
            vo.setCatelogId(item.getCatelogId());
            // 查询该分组所绑定的属性的id
            List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", item.getAttrGroupId()));
            // 把attr的id提取出来
            List<Long> attrIds  = relationList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            // 把这些id查出来
            List<AttrEntity> attrs = new ArrayList<>();
            if(!CollectionUtils.isEmpty(attrIds)){
                attrs = (List<AttrEntity>) attrService.listByIds(attrIds);
            }
            vo.setAttrs(attrs);
            return vo;
        }).collect(Collectors.toList());
        return RespBean.success("获取成功",result);
    }

}